import Schema, { Rules, Values } from "async-validator";
import { Context } from "koa";
import { accessLogger } from "../app/logger";

/*
 * @Author: DUST
 * @Date: 2023-05-28 10:23:34
 * @LastEditors: DUST
 * @LastEditTime: 2023-05-31 14:11:39
 * @FilePath: \koa-node-ts\utils\validator.ts
 * @Description:
 * undefined
 */
/**
 * @description: 参数校验
 * @param {Context} ctx：请求体
 * @param {Rules} rules：校验规则
 * @param {boolean} flag：是否显示却不校验信息
 * @return {*} 校验结果
 */
async function validate<T extends Values>( ctx: Context, rules: Rules, flag: boolean = false ): Promise<{ data: T; msg: string | null }> {
  const validator = new Schema(rules);
  // 需要校验参数
  let data = getParams(ctx);

  return await validator
    .validate(data)
    .then(() => {
      return {
        data,
        msg: null,
      };
    })
    .catch((err) => {
      console.log(JSON.stringify(data));
      accessLogger.error(err);
      if (flag) {
        return {
          data: data,
          msg: err,
        };
      }
      return {
        data: data,
        msg: err.errors[0].message,
      };
    });
}
/**
 * @description: 根据请求类型返回请求的参数
 * @param {Context} ctx：请求体
 * @return 获取请求的参数
 */
export function getParams(ctx: Context) {
  let data: any;
  switch (ctx.method) {
    case "GET":
      data = new URLSearchParams(ctx.querystring) || {}
      break;
    case "POST":
      data = ctx.request.body || {}
      break;
    case "PUT":
      data = ctx.request.body || {}
      break;
    case "DELETE":
      data = ctx.querystring || {}
      break;
    default:
      data = {}
      break;
  }
  accessLogger.info(`请求路径：${ctx.path}；请求类型：${ctx.method}；请求参数：${JSON.stringify(data)}；请求头：${JSON.stringify(ctx.header)}`);
  return data;
}

export default validate;
